<?php
/**
 * Json Web Token 帮助类
 * User: 苏近之
 * Date: 2019-03-24
 * Time: 02:47
 */

namespace app\common\helper;

use app\common\exception\AuthTokenVerifyFailed;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Rsa\Sha256;
use Lcobucci\JWT\ValidationData;
use think\facade\Config;

class JwtToken
{

    /**
     * 构建 Token
     * @param int $userId
     * @param int $expire
     * @return \Lcobucci\JWT\Token
     */
    public static function builder(int $userId, int $expire = 3600)
    {
        $currentTimestamp = time();

        return (new Builder())->setIssuer(Config::get('app.app_host'))
            ->setIssuedAt($currentTimestamp)
            ->setNotBefore($currentTimestamp)
            ->setExpiration($currentTimestamp + $expire)
            ->set('user_id', $userId)
            ->getToken();
    }

    /**
     * 校验 Token
     * @param string $token
     * @return mixed
     * @throws AuthTokenVerifyFailed
     */
    public static function verify(string $token)
    {
        $token = (new Parser())->parse($token);
        $data = new ValidationData();
        $data->setIssuer(Config::get('app.app_host'));

        if (!$token->validate($data)) {
            throw new AuthTokenVerifyFailed();
        }

        return $token->getClaim('user_id');
    }
}